package com.lisn.roomlib.FileInfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class FileInfoManager {

    //反序列,把二进制数据转换成java object对象
    private static Object toObject(byte[] data) {
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        try {
            bais = new ByteArrayInputStream(data);
            ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bais != null) {
                    bais.close();
                }
                if (ois != null) {
                    ois.close();
                }
            } catch (Exception ignore) {
                ignore.printStackTrace();
            }
        }
        return null;
    }

    //序列化存储数据需要转换成二进制
    private static <T> byte[] toByteArray(T body) {
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(body);
            oos.flush();
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (oos != null) {
                    oos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new byte[0];
    }

    public static void delete(String name, String path) {
        FileInfo fileInfo = new FileInfo();
        fileInfo.name = name;
        fileInfo.path = path;
        FileInfoDatabase.get().getFileInfoDao().delete(fileInfo);
    }

    public static void save(String name,
                            String path,
                            String time,
                            String type,
                            String thumbnail) {
        FileInfo fileInfo = new FileInfo();
        fileInfo.name = name;
        fileInfo.path = path;
        fileInfo.time = time;
        fileInfo.type = type;
        fileInfo.thumbnail = thumbnail;

        FileInfoDatabase.get().getFileInfoDao().save(fileInfo);
    }

    public static FileInfo getFileInfo(String key) {
        FileInfo fileInfo = FileInfoDatabase.get().getFileInfoDao().getFileInfo(key);
        if (fileInfo != null && fileInfo.path != null) {
            return fileInfo;
        }
        return null;
    }
}
